import collections
class Solution(object):
    def findAllPeople(self, n, meetings, firstPerson):
        time_list = [t for _, _, t in meetings]
        time_list = list(set(time_list))
        time_list.sort()
        d = collections.defaultdict(list)
        for u, v, t in meetings:
            d[t].append((u, v))
        a_set = {0, firstPerson}
        def find(x):
            if p[x] == x:
                return p[x]
            else:
                p[x] = find(p[x])
                return p[x]
            
        def union(x, y):
            rx = find(x)
            ry = find(y)
            if rx != ry:
                if rx > ry:
                    p[rx] = ry
                else:
                    p[ry] = rx

        for t in time_list:
            now_p = d[t]
            p = {}
            q = collections.defaultdict(set)
            c = collections.defaultdict(int)
            for u, v in now_p:
                if u not in p:
                    p[u] = u
                if v not in p:
                    p[v] = v
                union(u, v)
            for key in p:
                q[find(key)].add(key)
                if key in a_set:
                    c[find(key)] = 1
            for key in q:
                if c[key]:
                    a_set.update(q[key])
        return list(a_set)


data = Solution()
n = 6
meetings = [[1,2,5],[2,3,8],[1,5,10]]
firstPerson = 1
print(data.findAllPeople(n, meetings, firstPerson))